<template>
  <div class="hr-interview-analysis-container">
    <div class="page-header">
      <a-button type="text" @click="goBack" style="margin-right: 16px">
        <template #icon><arrow-left-outlined /></template>
        返回
      </a-button>
      <h2 v-if="analysisData">HR面试分析报告</h2>
    </div>

    <a-spin :spinning="loading" tip="加载分析数据中...">
      <div v-if="analysisData" class="analysis-content-wrapper">
        <a-row :gutter="24">
          <!-- 左侧：面试结果和评分 -->
          <a-col :xs="24" :md="10">
            <a-card class="result-card">
              <h3>HR面试结果</h3>
              <div class="result-summary">
                <a-alert
                  :type="isInterviewPassed ? 'success' : 'error'"
                  :message="isInterviewPassed ? '面试结果：通过' : '面试结果：未通过'"
                  :description="
                    isInterviewPassed
                      ? '候选人HR面试能力达到要求标准'
                      : '候选人HR面试能力未达到要求标准'
                  "
                  show-icon
                  style="margin-bottom: 16px"
                />
                <div class="total-score">
                  <span>总分：</span>
                  <span
                    class="score-number"
                    :style="{ color: getTotalScoreColor(analysisData.totalScore) }"
                    >{{ analysisData.totalScore }}</span
                  >
                  <span class="score-unit">/100</span>
                </div>
              </div>

              <a-row :gutter="16">
                <a-col :span="24" v-for="(score, index) in parsedScores" :key="index">
                  <a-card class="score-card">
                    <div class="score-header">
                      <span class="question-index">问题 {{ index + 1 }}</span>
                      <a-tag :color="getScoreColor(score)">{{ score }} 分</a-tag>
                    </div>
                    <div class="score-bar-container">
                      <div
                        class="score-bar"
                        :style="{ width: `${score * 10}%`, backgroundColor: getScoreColor(score) }"
                      ></div>
                      <div class="score-threshold" :style="{ left: '60%' }"></div>
                    </div>
                    <div class="score-labels">
                      <span>0</span>
                      <span class="threshold-label">及格线 (6分)</span>
                      <span>10</span>
                    </div>
                  </a-card>
                </a-col>
              </a-row>

              <div class="communication-ability">
                <h3>沟通能力评估</h3>
                <a-card>
                  <div v-if="communicationAbility">
                    <p><strong>表情情绪：</strong>{{ communicationAbility?.microExpression }}</p>
                    <p><strong>语音情绪：</strong>{{ communicationAbility?.audioEmotion }}</p>
                    <p><strong>语速：</strong>{{ communicationAbility?.speechRate }}</p>
                    <p><strong>面部动作：</strong>{{ communicationAbility?.facialActions }}</p>
                    <p><strong>躯体动作：</strong>{{ communicationAbility?.bodyMovements }}</p>
                    <p>
                      <strong>沟通总结：</strong>{{ communicationAbility?.communicationSummary }}
                    </p>
                  </div>
                </a-card>
              </div>

              <a-card class="multimodal-summary-card">
                <h3>多模态表现总结</h3>
                <p>{{ analysisData.overallMultimodalSummary }}</p>
              </a-card>
            </a-card>
          </a-col>

          <!-- 右侧：问题详情和多模态分析 -->
          <a-col :xs="24" :md="14">
            <a-card class="questions-card">
              <h3>面试问答记录</h3>
              <a-timeline class="interview-timeline">
                <a-timeline-item v-for="(item, index) in parsedQuestionList" :key="index">
                  <div class="timeline-item interviewer">
                    <span class="speaker">面试官</span>
                    <div class="content">{{ item.question }}</div>
                  </div>
                  <div class="timeline-item candidate">
                    <span class="speaker">候选人</span>
                    <div class="content">{{ item.answer }}</div>
                  </div>
                  <div class="timeline-item analysis">
                    <div class="analysis-header">
                      <span class="analysis-title">情绪分析</span>
                    </div>
                    <div class="analysis-content">
                      <a-descriptions bordered :column="1" size="small">
                        <a-descriptions-item label="微表情">
                          {{ item.emotionDetails[0]?.microExpression || '-' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="语音情绪">
                          {{ item.emotionDetails[0]?.audioEmotion || '-' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="一致性">
                          {{ item.emotionDetails[0]?.consistency || '-' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="面部动作">
                          {{ item.emotionDetails[0]?.facialActions || '-' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="肢体动作">
                          {{ item.emotionDetails[0]?.bodyMovements || '-' }}
                        </a-descriptions-item>
                      </a-descriptions>
                      <p class="evaluation-summary">
                        <strong>评估总结:</strong> {{ item.answerEvaluationSummary }}
                      </p>
                    </div>
                  </div>
                </a-timeline-item>
              </a-timeline>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 无数据提示 -->
      <a-empty v-if="!loading && !analysisData" description="暂无分析数据" />
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Button as AButton,
  Card as ACard,
  Row as ARow,
  Col as ACol,
  Timeline as ATimeline,
  TimelineItem as ATimelineItem,
  Tag as ATag,
  Alert as AAlert,
  Descriptions as ADescriptions,
  DescriptionsItem as ADescriptionsItem,
  Spin as ASpin,
  Empty as AEmpty,
} from 'ant-design-vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { getHrInterviewAnalyzeResultUsingGet } from '@/api/hrInterviewController'

const route = useRoute()
const router = useRouter()
const id = route.query.id

const loading = ref(true)
const analysisData = ref<any>(null)

const goBack = () => {
  router.go(-1)
}

// 解析问题列表数据
const parsedQuestionList = computed(() => {
  if (!analysisData.value || !analysisData.value.questionList) return []
  try {
    return JSON.parse(analysisData.value.questionList)
  } catch (e) {
    console.error('解析问题列表数据出错:', e)
    return []
  }
})

// 解析沟通能力数据
const communicationAbility = computed(() => {
  if (!analysisData.value || !analysisData.value.communicationAbility) return null
  try {
    return JSON.parse(analysisData.value.communicationAbility)
  } catch (e) {
    console.error('解析沟通能力数据出错:', e)
    return null
  }
})

// 解析分数数据
const parsedScores = computed(() => {
  if (!analysisData.value || !analysisData.value.scores) return []
  try {
    return JSON.parse(analysisData.value.scores).map((score: string) => parseFloat(score))
  } catch (e) {
    console.error('解析分数数据出错:', e)
    return []
  }
})

// 判断面试是否通过（所有题目分数都超过6分）
const isInterviewPassed = computed(() => {
  if (!analysisData.value || !analysisData.value.totalScore) return false
  return parseFloat(analysisData.value.totalScore) >= 60
})

/**
 * 根据分数获取颜色
 * @param {number|string} score 分数
 * @returns {string} 颜色代码
 */
const getScoreColor = (score: number | string) => {
  const numScore = typeof score === 'string' ? parseFloat(score) : score
  if (numScore >= 8) return '#52c41a'
  if (numScore >= 7) return '#1890ff'
  if (numScore >= 6) return '#faad14'
  return '#f5222d'
}

/**
 * 根据总分获取颜色
 * @param {number|string} score 总分
 * @returns {string} 颜色代码
 */
const getTotalScoreColor = (score: number | string) => {
  const numScore = typeof score === 'string' ? parseFloat(score) : score
  if (numScore >= 80) return '#52c41a'
  if (numScore >= 70) return '#1890ff'
  if (numScore >= 60) return '#faad14'
  return '#f5222d'
}

/**
 * 获取面试分析数据
 */
const fetchAnalysisData = async () => {
  if (!id) {
    loading.value = false
    return
  }

  loading.value = true
  try {
    // @ts-ignore - Ignoring type errors for API call
    const response = await getHrInterviewAnalyzeResultUsingGet({
      hrInterviewId: id as any,
    })

    // API response structure is { code: number, data: object, message: string }
    if (response.code === 0 && response.data) {
      analysisData.value = response.data
    } else {
      console.error('获取HR面试分析数据失败:', response.message)
    }
  } catch (error) {
    console.error('获取HR面试分析数据出错:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAnalysisData()
})
</script>

<style scoped>
.hr-interview-analysis-container {
  padding: 20px;
  background: linear-gradient(to right, #f8f9fa 0%, #f1f3f5 100%);
  min-height: 100vh;
  overflow-y: auto;
  max-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.analysis-content-wrapper {
  margin-bottom: 20px;
}

.result-card,
.questions-card,
.multimodal-summary-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.result-card h3,
.questions-card h3,
.multimodal-summary-card h3 {
  font-size: 18px;
  color: #1890ff;
  margin-bottom: 16px;
}

.score-card {
  margin-bottom: 16px;
}

.score-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-index {
  font-weight: 500;
  color: #333;
}

.score-bar-container {
  position: relative;
  height: 10px;
  background-color: #f0f0f0;
  border-radius: 5px;
  margin: 10px 0;
  overflow: hidden;
}

.score-bar {
  height: 100%;
  border-radius: 5px;
  transition: width 0.5s ease;
}

.score-threshold {
  position: absolute;
  top: 0;
  width: 2px;
  height: 100%;
  background-color: #000;
  z-index: 1;
}

.score-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.threshold-label {
  position: absolute;
  left: 60%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #666;
}


.score-number {
  font-size: 24px;
  font-weight: bold;
}

.result-summary {
  margin-bottom: 20px;
}

.communication-ability {
  margin: 20px 0;
}

.communication-ability p {
  margin-bottom: 8px;
}

.interview-timeline {
  margin-top: 16px;
}

.timeline-item {
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 8px;
}

.timeline-item.interviewer {
  background-color: #f0f7ff;
  border-left: 3px solid #1890ff;
}

.timeline-item.candidate {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.timeline-item.analysis {
  background-color: #fcfcfc;
  border-left: 3px solid #722ed1;
  margin-bottom: 24px;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.analysis-title {
  font-weight: 500;
  color: #333;
}

.analysis-content {
  color: #666;
}

.evaluation-summary {
  margin-top: 16px;
  font-size: 14px;
  line-height: 1.6;
}

.speaker {
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  display: block;
}

.content {
  color: #666;
  line-height: 1.6;
}

.multimodal-summary-card {
  background-color: #fff;
  padding: 16px;
}

.multimodal-summary-card p {
  font-size: 14px;
  line-height: 1.8;
  color: #333;
}

.total-score {
  margin-top: 16px;
  font-size: 16px;
  text-align: center;
}

.score-unit {
  font-size: 12px;
  color: #666;
}

@media (max-width: 768px) {
  .hr-interview-analysis-container {
    padding: 16px;
  }
}
</style>
